package es.onlysolutions.gs.web.validator;

import es.onlysolutions.gs.web.commandBean.RegisterBean;
import es.onlysolutions.gs.comm.facade.UserFacade;
import es.onlysolutions.gs.comm.entity.User;
import es.onlysolutions.arq.core.mvc.command.AbstractCommandBean;
import org.springframework.validation.Errors;

/**
 * Validator for the register of a new account.
 */
public class RegisterValidator extends GSValidator
{

    private UserFacade userFacade;

    public void setUserFacade(UserFacade userFacade)
    {
        this.userFacade = userFacade;
    }

    public boolean supports(Class aClass)
    {
        return RegisterBean.class == aClass;
    }

    protected void validateForm(AbstractCommandBean abstractCommandBean, Errors errors)
    {
        RegisterBean bean = (RegisterBean) abstractCommandBean;
        User user = (User) bean.getEntidad();

        boolean login = rejectIfEmptyOrWhitespace(errors, "entidad.login", "fieldRequired", new String[]{"Login"}, "The field {0} is required");
        boolean password = rejectIfEmptyOrWhitespace(errors, "entidad.password", "fieldRequired", new String[]{"Password"}, "The field {0} is required");

        boolean email = rejectIfEmptyOrWhitespace(errors, "entidad.email", "fieldRequired", new String[]{"Email"}, "The field {0} is required");

        if( email )
        {
            validarEmail(errors, "entidad.email", "Email", user.getEmail(), 100, false);
        }

        if( login && userFacade.getExistUser( user.getLogin() ) )
        {
            errors.rejectValue("entidad.login", "user.loginRepeated", new String[]{user.getLogin()}, "The user {0} currently exists");
        }

    }
}
